const BASE_URL = '/ncpsy';
$(document).ready(function () {
	// 动态添加下拉框
	var selectOptions = [];
// 获取运输商列表,并渲染
	getTransportList().then(res => {
		selectOptions = res;
		renderAll();
	}).catch(err => console.log(err));
	function renderAll() {
		selectEl = `<div class="layui-form-item">
    <label class="layui-form-label">选择运输商</label>
    <div class="layui-input-block">
      <select class="drawer-select" name="qid" lay-verify="required">
        <option value="">请选择</option>
        ${renderSelectOptions(selectOptions)}
      </select>
    </div>
  </div>`;
		// 添加环节
		huanjieHtml = `<div class="addItemWrap">
                <div class="header">
                  <i aria-label="图标: unordered-list" class="anticon anticon-unordered-list"
                     style="font-size: 16px;">
                    <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="unordered-list" width="1em"
                         height="1em" fill="currentColor" aria-hidden="true">
                      <path d="M912 192H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 284H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 284H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM104 228a56 56 0 1 0 112 0 56 56 0 1 0-112 0zm0 284a56 56 0 1 0 112 0 56 56 0 1 0-112 0zm0 284a56 56 0 1 0 112 0 56 56 0 1 0-112 0z"></path>
                    </svg>
                  </i>
                </div>
                <div class="content">
                  <div class="layui-form-item">
                    <label class="layui-form-label">环节名称：</label>
                    <div class="layui-input-block">
                      <input type="text" name="lname" required lay-verify="required" placeholder="请输入"
                             autocomplete="off" class="layui-input">
                    </div>
                  </div>
                  ${selectEl}
                  <div class="layui-form-item">
                    <label class="layui-form-label">环节说明：</label>
                    <div class="layui-input-block">
                      <input type="text" name="nexplain" required lay-verify="required" placeholder="请输入"
                             autocomplete="off" class="layui-input">
                    </div>
                  </div>
                </div>
                <div class="delete delete-huanjie-template"><a>删除</a></div>
              </div>`;
	}
	let huanjieHtml, selectEl;
	// 添加环节按钮事件
	$('.add-huanjie-template').on('click', function (e) {
		const newTraceScrollWrap = $('.newTraceScrollWrap');
		if (newTraceScrollWrap.children().length >= 10) {
			return false
		}
		const $newTemp = document.createElement('div');
		$newTemp.setAttribute('class', 'new-add-huanjie-template-wrapper');
		$newTemp.innerHTML = huanjieHtml;
		newTraceScrollWrap.append($newTemp)
	});

	/*
	* 新建、查看、编辑模板页面操作
	* */
	$('body').on('click', '.delete-huanjie-template',  function(e) { // 删除单个环节
		$(this).parents('.new-add-huanjie-template-wrapper').remove();
	})
		.on('click', '.ant-drawer-close', function () { // 关闭新建、编辑、查看模板
			$(this).parents('.drawer-right').fadeOut()
		})
		.on('click', '.cancel-add-template', function () { // 取消新建、编辑模板
			$(this).parents('.drawer-right').fadeOut()
		})
		.on('click', '.drawer-mask', function () { // 点击mask遮罩关闭右侧页面
			$(this).parents('.drawer-right').fadeOut()
		})
		.on('change', '.drawer-select', function () {
			console.log($(this).val())
		})
		.on('click', '.confirm-add-template', function () { // 确认添加环节模板
			const arr = $('form').serializeArray();
			let tpName = arr[0].value;
			if (!tpName) {
				layer.msg('请输入模板名称');
				return false
			}
			let nodeList = [];
			if (arr.length > 1) {
				for (let i = 1, len = arr.length; i < len; i += 3) {
					const obj = {};
					obj[arr[i].name] = arr[i].value;
					obj[arr[i+1].name] = arr[i+1].value;
					obj[arr[i+2].name] = arr[i+2].value;
					nodeList.push(obj)
				}
			}
			var qyid = localStorage.getItem('qyid');
			const data = {
				tpName,
				nodeList: nodeList,
				qyid
			};
			submitNewTemplate(data)
		});

	// 提交到后台
	function submitNewTemplate(data) {
		$.ajax({
			type: 'post',
			url: BASE_URL + '/addTp',
			contentType: 'application/json;charset=utf-8',
			data: JSON.stringify(data),
			success(res) {
				if (res.code === 200) {
					layer.msg(res.message, {icon: 6});
					hideTemplate('.new-template-container'); // 关闭右侧页面
					updateTamplateTable(); // 更新模板列表
				}
			},
			error(err) {
				console.log(err)
			}
		})
	}

	// 新建模板
	$('.add-template-btn').on('click', function () {
		showTemplate('.new-template-container');
		console.log(selectOptions)
	});
});

// 显示模板
function showTemplate(el) {
	$(el).fadeIn()
}
// 关闭模板
function hideTemplate(el) {
	$(el).fadeOut()
}

// 运输商列表HTML
function renderSelectOptions(data) {
	if (!data || !data.length) {
		return false
	}
	let select = '';
	for (let i = 0, len = data.length; i < len; i ++) {
		const $option = `<option value="${data[i].qyid}">${data[i].qymc}</option>`;
		select += $option
	}
	return select
}


// 查看————获取模板环节信息并渲染到页面
function renderHuanjieDataView(data) {
	// 先清空元素内容，再渲染
	const viewLayUITimeLine = $('.viewLayUITimeLine');
	viewLayUITimeLine.empty();
	$('.viewTemplateName').text(data.tpName);
	const list = data.nodeList;
	if (!list || !list.length) {
		return false
	}
	for (let i = 0, len = list.length; i < len; i ++) {
		const $el = `<li class="layui-timeline-item">
            <i class="layui-icon layui-timeline-axis">&#xe63f;</i>
            <div class="layui-timeline-content layui-text">
              <h3 class="layui-timeline-title">${list[i].lname}</h3>
              <p>
                环节描述：${list[i].nexplain}
              </p>
            </div>
          </li>`;
		viewLayUITimeLine.append($el)
	}
}

// 获取运输商列表
function getTransportList() {
	return new Promise((resolve, reject) => {
		$.ajax({
			url: BASE_URL + '/queryUserOne/2',
			type: 'get',
			contentType: 'application/json;charset=utf-8;',
			success: function(res) {
				if (res.code === 200) {
					resolve(res.data);
				}
			},
			error(err) {
				reject(err)
			}
		})
	})
}




/*
// 编辑环节时，渲染获取的环节
// todo: 获取后台环节list
const huanjieListData = {
	name: '模板名称',
	list: [
		{
			name: '环节名称1',
			description: '环节描述1'
		},
		{
			name: '环节名称2',
			description: '环节描述2'
		},{
			name: '环节名称3',
			description: '环节描述3'
		},{
			name: '环节名称4',
			description: '环节描述4'
		}
	]
};

// 编辑————获取模板环节信息并渲染到页面
function renderHuanjieDataEdit(data) {
	const $el = `<div class="layui-form-item">
                <label class="layui-form-label">模板名称：</label>
                <div class="layui-input-block">
                  <input type="text" name="title" required lay-verify="required" placeholder="请输入" autocomplete="off"
                         class="layui-input" value="${data.name}">
                </div>
              </div>`;
	// 先清空元素内容，再渲染
	const editTraceScrollWrap = $('.editTraceScrollWrap');
	editTraceScrollWrap.empty().append($el);
	if (!data.list || !data.list.length) {
		return false
	}
	for (let i = 0, len = data.list.length; i < len; i ++) {
		const $el = `<div class="new-add-huanjie-template-wrapper"><div class="addItemWrap">
                <div class="header">
                  <i aria-label="图标: unordered-list" class="anticon anticon-unordered-list"
                     style="font-size: 16px;">
                    <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="unordered-list" width="1em"
                         height="1em" fill="currentColor" aria-hidden="true">
                      <path d="M912 192H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 284H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 284H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM104 228a56 56 0 1 0 112 0 56 56 0 1 0-112 0zm0 284a56 56 0 1 0 112 0 56 56 0 1 0-112 0zm0 284a56 56 0 1 0 112 0 56 56 0 1 0-112 0z"></path>
                    </svg>
                  </i>
                </div>
                <div class="content">
                  <div class="layui-form-item">
                    <label class="layui-form-label">环节名称：</label>
                    <div class="layui-input-block">
                      <input type="text" name="title" required lay-verify="required" placeholder="请输入"
                             autocomplete="off" class="layui-input" value="${data.list[i].name}">
                    </div>
                  </div>
                  ${selectEl}
                  <div class="layui-form-item">
                    <label class="layui-form-label">环节说明：</label>
                    <div class="layui-input-block">
                      <input type="text" name="title" required lay-verify="required" placeholder="请输入"
                             autocomplete="off" class="layui-input" value="${data.list[i].description}">
                    </div>
                  </div>
                </div>
                <div class="delete delete-huanjie-template"><a>删除</a></div>
              </div></div>`;
		editTraceScrollWrap.append($el)
	}
}*/


